package com.alg.array;

/**
 * @author sc
 * Created on  2018/9/28
 */
public  class Array<E> {
    private E[] data;
    private int size;

    public Array(int capacity){
        data = (E[])new Object[capacity];
        size=0;
    }

    public Array(){
        this(10);
    }

    public int getSize(){
        return size;
    }

    public int getCapacity(){
        return data.length;
    }

    public boolean isEmpty(){
        return size==0;
    }

    public void addLast(E e){
        addOnPosition(e,size);
    }

    public void addFirst(E e){
        addOnPosition(e,0);
    }

    public void addOnPosition(E e,int pos){
        if(size==data.length){
            resize(data.length*2);
        }

        if(pos>=data.length||pos<0){
            throw new IllegalArgumentException("param is error");
        }
        for(int i=size-1;i>=pos;i--){
            data[i+1]=data[i];
        }
        data[pos]=e;
        size++;
    }

    private void resize(int size) {
        E[] newData = (E[]) new Object[size];
        for (int i = 0; i < data.length; i++) {
            newData[i]=data[i];
        }
        data=newData;
    }


    public E get(int index){
        if(index<0||index>=size){
            throw new IllegalArgumentException("索引越界");
        }
        return data[index];
    }

    public void set(E e,int index){
        if(index<0||index>=size){
            throw new IllegalArgumentException("索引越界");
        }
        data[index]=e;
    }

    public boolean contains(E e){
        for (E item : data) {
            if(item==e){
                return true;
            }
        }
        return false;
    }

    public int find(E e){
        for (int i = 0; i < size; i++) {
            if(data[i]==e){
                return i;
            }
        }
        return -1;
    }


    public E removeOnPosition(int index){
        if(index<0||index>=size){
            throw new IllegalArgumentException("索引越界");
        }
        E res = data[index-1];
        for(int i=index-1;i<size;i++){
            data[i]=data[i+1];
        }
        size--;
        data[size]=null;
        if(size==data.length/4){
            resize(data.length/2);
        }
        return res;
    }

    public E removeFirst(){
       return removeOnPosition(0);
    }

    public E removeLast(){
       return removeOnPosition(size-1);
    }

    public void removeElement(E e){
        int index = find(e);
        removeOnPosition(index);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("Array size=%d,capacity=%d\n",size,data.length));
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(data[i]);
            if(i!=size-1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
